import {
  userGetUserInfo,
  getpcindex_new
} from '@/assets/api/indexApi.js'

import {
  getzegotoken_chat
} from '@/assets/api/csjhApi';

export const state = () => ({
  signShow: false,
  vipNoTimeShow: false,
  payVipShow: false,
  payVipIndex: 1,
  test: 'testvuex',
  logo_color: '',
  nav_color: '',
  back_color: '',
  // 导航栏选择的下标
  menuIndex: '0',
  // 导航栏数组
  meunListSbPosition: {
    '1': [0, 2, 1, 3, 6, 4, 5, 7],
    '2': [0, 3, 2, 1, 4, 5, 6, 7],
    '3': [0, 5, 2, 1, 6, 7, 3, 4],
    '4': [0, 5, 7, 2, 4, 6, 3, 1],
    '5': [0, 4, 5, 2, 6, 7, 1, 3],
    '6': [0, 2, 7, 3, 1, 4, 5, 6],
  },
  menuListSb: [{
      name: '首页',
      path: '/',
      isLogin: false,
      list: []
    }, {
      name: '财税AI',
      path: '/chatgpt/xzcsgpt',
      isLogin: false,
      list: []
    }, {
      name: '专业知识',
      path: '/school/vipzjkc',
      isLogin: false,
      list: [{
        name: '小竹学院',
        path: '/indices/xzxy',
        pathName: 'indices-xzxy'
      }, {
        name: '会计考证',
        path: '/indices/xzxy-xzzy?type=1',
        pathName: 'indices-xzxy-xzzy'
      }, {
        name: '实操课程',
        path: '/indices/xzxy-xzzy?type=2',
        pathName: 'indices-xzxy-xzzy'
      }, {
        name: '专家问答',
        path: '/cswd',
        pathName: 'cswd'
      }]
    }, {
      name: '工作助手',
      path: '/chatgpt/xzcsgpt',
      isLogin: false,
      list: [{
        name: '模板库',
        path: '/templates',
        pathName: 'templates'
      }, {
        name: '税收法规库',
        path: '/ssfgk/index/0/1',
        pathName: 'ssfgk-type-indexTwo-page'
      }, {
        name: '会计法规库',
        path: '/kjfgk/index/0/1',
        pathName: 'kjfgk-type-indexTwo-page'
      }, {
        name: '问题库',
        path: '/quizdata',
        pathName: 'quizdata'
      }, {
        name: '发票整理助手',
        path: '/tools/invoiceassistant',
        pathName: 'Tools-type'
      }, {
        name: '各类计算器',
        path: '/tools/taxcount',
        pathName: 'Tools-type'
      }]
    }, {
      name: '会计影响力',
      path: '/chatgpt/xzcsgpt',
      isLogin: false,
      list: [{
        name: '跨部门沟通',
        path: '',
        noPath: true,
        pathName: ''
      }, {
        name: '如何搞定销售',
        path: '/school/vipzjkc',
        pathName: 'school-type'
      }, {
        name: '如何搞定老板',
        path: '/school/vipzjkc',
        pathName: 'school-type'
      }, {
        name: '对外社交',
        path: '',
        noPath: true,
        pathName: ''
      }, {
        name: '当众表达',
        path: '',
        noPath: true,
        pathName: ''
      }, ]
    }, {
      name: '职业发展',
      path: '/chatgpt/xzcsgpt',
      isLogin: false,
      list: [{
        name: '财税政策解读',
        path: '/viponly',
        pathName: 'viponly'
      }, {
        name: '税务筹划实战运用',
        path: '/school/vipzjkc',
        pathName: 'school-type'
      }, {
        name: '如何快速晋升',
        path: '/school/vipzjkc',
        pathName: 'school-type'
      }, {
        name: '自身风险规避',
        path: '/school/vipzjkc',
        pathName: 'school-type'
      }, {
        name: '股权设计',
        path: '/school/vipzjkc',
        pathName: 'school-type'
      }, ]
    }, {
      name: '财税圈子',
      path: '/chatgpt/xzcsgpt',
      isLogin: false,
      list: [{
        name: '法律答疑',
        path: '/indices/fldy',
        pathName: 'indices-fldy',
      }, {
        name: '快乐驿站',
        path: '/happlypost/page/index',
        pathName: 'happlypost-page-page',
      }, {
        name: '财税资讯',
        path: '/information/rmzx/1',
        pathName: 'information-type-page'
      }]
    }, {
      name: '工商企服',
      path: '/service',
      isLogin: false,
      list: [{
        name: '企业体检报告',
        path: '/riskdetection',
        pathName: 'riskdetection'
      }, {
        name: '账户快开',
        path: '/openaccount',
        pathName: 'openaccount'
      }, {
        name: '工商代办',
        path: '/service',
        pathName: 'service'
      }, {
        name: '代理记账',
        path: '/service',
        pathName: 'service'
      }]
    },
    // {
    //   name: '会员中心',
    //   path: '/vipcenter',
    //   isLogin: false,
    //   list: []
    // }

  ],
  menuList: [
    // {
    //   name: '财税AI',
    //   index: '9',
    //   path: '/chatgpt/xzcsgpt',
    //   hot: true,
    //   list: [],
    // },
    // {
    //   name: '问题库',
    //   index: '1',
    //   path: '/quizdata',
    //   hot: false,
    //   list: [],
    // },
    {
      name: '小竹问答',
      index: '1',
      path: '/cswd',
      hot: false,
      list: [
        // {
        //   name: '快速提问',
        //   index: '20',
        //   path: 'cswd-ask',
        //   params: {},
        //   query: {},
        //   msg: '急速应答实时解惑'
        // },
        // {
        //   name: '专家提问',
        //   index: '21',
        //   path: 'cswd-tab-page',
        //   params: {
        //     page: '1',
        //     tab: 'zjwd'
        //   },
        //   query: {},
        //   msg: '定向选择信任的专家，跟有丰富实战经验的大咖、专家在线沟通，一对一实时解决财税问题'
        // },
        // {
        //   name: '精选问题',
        //   index: '22',
        //   path: 'cswd-tab-page',
        //   params: {
        //     page: '1',
        //     tab: 'jxhd'
        //   },
        //   query: {},
        //   msg: '财税问题全覆盖，实时问答有回应，答案效力有保障'
        // },
        // {
        //   name: '等你来答',
        //   index: '23',
        //   path: 'cswd-tab-page',
        //   params: {
        //     page: '1',
        //     tab: 'dnld'
        //   },
        //   query: {},
        //   msg: '加入我们成为专业老师'
        // },
      ],
    },
    {
      name: '财税库',
      index: '2',
      path: '/ssfgk/index/0/1',
      list: [{
        name: '税收法规库',
        index: '20',
        path: 'ssfgk-type-indexTwo-page',
        params: {
          type: 'index',
          indexTwo: '0',
          page: '1'
        },
        query: {},
        msg: '在收录时会确保政策原文准确无误，并结合专家解读明确政策要点和适用场景。'
      }, {
        name: '会计法规库',
        index: '21',
        path: 'kjfgk-type-indexTwo-page',
        params: {
          type: 'index',
          indexTwo: '0',
          page: '1'
        },
        query: {},
        msg: '在云端的加持下，不断补充扩增最新最全的会计政策'
      }, {
        name: '问题库',
        index: '22',
        path: 'quizdata',
        params: {},
        query: {},
        msg: '每个问题都有回答依据，有财税问题就来问题库精准搜索。'
      }, ],
    },
    // {
    //   name: '会计法规库',
    //   index: '4',
    //   path: '/kjfgk/index/0/1',
    //   list: [],
    // },

    { // 修改这个位置要去页面改个data
      name: '模板专区',
      index: '50',
      path: '/templates',
      list: [{
          name: '财税表单',
          index: '51',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '1',
            s_tid: '2',
            page: 1
          },
          query: {},
          msg: '小竹财税财税表单版块，财税表单、财税表格案例，其中包含财务与税务各类表单'
        },
        {
          name: '规章制度',
          index: '52',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '2',
            s_tid: '6',
            page: 1
          },
          query: {},
          msg: '小竹财税企业规章制度版块，企业规章制度案例，企业经营管理、内部控制的各项规章制度'
        },

        {
          name: '合同范本',
          index: '53',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '3',
            s_tid: '12',
            page: 1
          },
          query: {},
          msg: '小竹财税企业合同范本版块，包含市场经营活动中常见的合同模板'
        },
        {
          name: '办公常用',
          index: '54',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '12',
            s_tid: '30',
            page: 1
          },
          query: {},
          msg: '小竹财税办公常用表格下载版块，人事行政常用表单案例及企业日常办公用的统计及汇报'
        },
        {
          name: '毕业季',
          index: '55',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '11',
            s_tid: '9',
            page: 1
          },
          query: {},
          msg: '小竹财税毕业季常用表格下载版块，毕业季常用表格下载案例及毕业开题报告、答辩PPT以及简历模板'
        },
        // {
        //   name: '财税干货分享',
        //   index: '56',
        //   path: 'templates-modelarea-tid-s_tid-page',
        //   params: {
        //     tid: '8',
        //     s_tid: '36',
        //     page: 1
        //   },
        //   query: {}
        // },
      ],
    },

    {
      name: '小竹学院',
      index: '6',
      path: '/school/vipzjkc',
      list: [{
          name: '全站通会员专属课程',
          pid: 2,
          index: '60',
          pathName: 'vipzjkc',
          path: 'school-type',
          params: {
            type: 'vipzjkc'
          },
          query: {
            index: '60'
          },
          msg: '本会员课程专为财税人员打造，涵盖专业提升、职业晋升、财税合规及职场跨部门沟通等全方位内容'
        },
        {
          name: '考证专题',
          pid: 3,
          index: '61',
          pathName: 'kzzt',
          path: 'school-type',
          params: {
            type: 'kzzt'
          },
          query: {
            index: '61'
          },
          msg: '以互联网平台为载体，输出财税知识视频的模块'
        },
        {
          name: '实操视频',
          type: 1,
          index: '62',
          pathName: 'scsp',
          path: 'school-type',
          noShow: true,
          params: {
            type: 'scsp'
          },
          query: {
            index: '62'
          },
          msg: '实操课程可以帮助会计人员更好地进行实际操作，提高工作效率'
        },
        {
          name: '考证题库',
          type: 2,
          index: '63',
          pathName: 'kztk',
          path: 'school-type',
          noShow: true,
          params: {
            type: 'kztk'
          },
          query: {
            index: '63'
          },
          msg: '小竹财税毕业季'
        },
        {
          name: '实操课程',
          type: 4,
          pid: 100,
          index: '64',
          pathName: 'sckc',
          path: 'school-type',
          // noShow: true,
          params: {
            type: 'sckc'
          },
          query: {
            index: '64'
          },
          msg: '实操课程可以帮助会计人员更好地进行实际操作，提高工作效率'
        },
        {
          name: '秒懂财税',
          pid: 2,
          index: '65',
          pathName: 'mdcs',
          path: 'school-type',
          params: {
            type: 'mdcs'
          },
          query: {
            index: '65'
          },
          msg: '通过短短一分钟的视频，可以快速了解财税知识是关于理财和税收方面的实用信息，并且明白它对于更好地管理个人或企业的财务以及确保合法纳税有何帮助'
        },

        // { name: '财税热点', pid: 1, index: '54', path: '/school' },
      ],
    },
    // {
    //   name: '活动中心',
    //   index: '7',
    //   path: '/eventcentre',
    //   list: [],
    // },

    {
      name: '小竹企服',
      index: '7',
      path: '/service',
      target: '_blank',
      list: [],
    },
    // {
    //   name: '小竹开户',
    //   index: '8',
    //   path: '/openaccount',
    //   list: [],
    // },
    {
      name: '财税百宝箱',
      index: '9',
      path: '/riskdetection',
      list: [{
        name: '税务风险检测',
        index: '90',
        path: 'riskdetection',
        params: {},
        query: {},
        msg: '避免财税风险，降低税务稽查，输出风险报告'
      }, {
        name: '发票助手',
        index: '91',
        path: 'Tools-type',
        params: {
          type: 'invoiceassistant'
        },
        query: {},
        msg: '防伪、查重复、快速录入，您的私人发票管家'
      }, {
        name: '工作助手',
        index: '92',
        path: 'Tools-type',
        params: {
          type: 'taxcount'
        },
        query: {},
        msg: '',
        miniList: [{
          name: '增值税计算器',
          link: '/tools/taxcount'
        }, {
          name: '违约金计算器',
          link: '/tools/deditcount'
        }, {
          name: '利息计算',
          link: '/tools/penalsum'
        }, {
          name: '房贷计算器',
          link: '/tools/homecount'
        }, {
          name: '社保计算',
          link: '/tools/securitycount'
        }, {
          name: '办税日历',
          link: '/tools/taxdate'
        }, {
          name: '个税计算器',
          link: '/tools/personaltax'
        }, {
          name: '税率查询',
          link: '/tools/taxsearch'
        }, ]
      }, {
        name: '法律答疑',
        index: '93',
        path: 'indices-fldy',
        params: {},
        query: {},
        msg: '免费法律咨询，详情点击'
      }, ],
    },

    // {
    //   name: '小竹资讯',
    //   index: '80',
    //   path: '/information/rmzx/1',
    //   list: [{
    //       name: '热门资讯',
    //       index: '80',
    //       path: 'information-type-page',
    //       params: {
    //         type: 'rmzx',
    //         page: '1'
    //       },
    //       query: {}
    //     },
    //     {
    //       name: '财政资讯',
    //       index: '81',
    //       path: 'information-type-page',
    //       params: {
    //         type: 'czzx',
    //         page: '1'
    //       },
    //       query: {}
    //     },
    //     {
    //       name: '考试资讯',
    //       index: '82',
    //       path: 'information-type-page',
    //       params: {
    //         type: 'kszx',
    //         page: '1'
    //       },
    //       query: {}
    //     },
    //     {
    //       name: '税局稽查',
    //       index: '83',
    //       path: 'information-type-page',
    //       params: {
    //         type: 'sjjc',
    //         page: '1'
    //       },
    //       query: {}
    //     },
    //     {
    //       name: '财税分享',
    //       index: '84',
    //       path: 'information-type-page',
    //       params: {
    //         type: 'ggwz',
    //         page: '1'
    //       },
    //       query: {}
    //     },
    //   ],
    // },
    // {
    //     name: '小竹企服',
    //     index: '8',
    //     path: '/service',
    //     list: [],
    // },
  ],

  // 登录弹窗显示
  loginShow: false,

  // 用户信息
  userInfo: null,

  // 底部是否出现在视窗中
  isFooterShow: false,

  // 浏览记录超过上限显示
  noViewShow: false,

  metaInfo: {},

  zim: null,

  // 未读消息数
  messageCount: {
    commentandlike: 0,
    comment: 0,
    dengnilaida: 0,
    inviteanswer: 0,
    like: 0,
    message: 0,
    question: 0,
    wendahuifu: 0,
    hd_unread: 0,
    xx_unread: 0,
    huiyuanzhuanxiang: 0
  },

  // 小竹问答热门标签
  hotTags: [],

  // 首页数据
  indexRes: null,

  // 首页数据
  indexHotSearch: null,

  // 会话列表
  conversationList: [],

  // zim是否登录
  zimStatus: false,

  goeasyObj: null


})

export const getters = {
  menuIndex: (state) => state.menuIndex,
  menuList: (state) => state.menuList,
  schoolList: (state) => state.menuList[6].list,

  loginShow: (state) => state.loginShow,
  userInfo: (state) => state.userInfo,

  isFooterShow: (state) => state.isFooterShow,

  noViewShow: (state) => state.noViewShow,
}

export const mutations = {
  setmenuIndex(state, menuIndex) {
    state.menuIndex = menuIndex
  },
  removeMenuIndex(state) {
    state.menuIndex = null
  },
  setloginShow(state, loginShow) {
    state.loginShow = loginShow
  },

  setuserInfo(state, userInfo) {
    state.userInfo = userInfo
  },

  setisFooterShow(state, isFooterShow) {
    state.isFooterShow = isFooterShow
  },

  setNoViewShow(state, noViewShow) {
    state.noViewShow = noViewShow
  },

  set_metaInfo(state, data) {
    state.metaInfo = data
  },

  set_zim(state, data) {
    console.log(data)
    state.zim = data
  },

  set_messageCount(state, data) {
    state.messageCount.commentandlike = parseInt(data.commentandlike)
    state.messageCount.message = parseInt(data.message)
    state.messageCount.dengnilaida = parseInt(data.dengnilaida)
    state.messageCount.comment = parseInt(data.comment)
    state.messageCount.like = parseInt(data.like)
    state.messageCount.inviteanswer = parseInt(data.inviteanswer)
    state.messageCount.question = parseInt(data.question)
    state.messageCount.wendahuifu = parseInt(data.wendahuifu)
    state.messageCount.huiyuanzhuanxiang = parseInt(data.huiyuanzhuanxiang)

  },
  set_messageCount2(state, data) {
    if (data.xx_unread || data.xx_unread === 0)
      state.messageCount.xx_unread = parseInt(data.xx_unread)
    if (data.hd_unread || data.hd_unread === 0)
      state.messageCount.hd_unread = parseInt(data.hd_unread)
  },

  set_hotTags(state, data) {
    state.hotTags = data
  },

  set_indexRes(state, data) {
    state.indexRes = data
  },

  set_conversationList(state, query) {
    let data = query.conversationList
    for (let item of data) {
      if (item.lastMessage) {
        let extendedData = JSON.parse(item.lastMessage.extendedData)
        if (extendedData.quiz_id) {
          query.zim.deleteConversation(item.conversationID, 0, {
            isAlsoDeleteServerConversation: true
          })
        }
      }
    }
    state.conversationList = data.sort((obj1, obj2) => {
      return obj2.orderKey - obj1.orderKey;
    })
  },

  set_zimStatus(state, data) {
    state.zimStatus = data
  },

  // 更新会话列表，接受一个数组
  updata_ConversationList(state, conversationList) {

    // state.conversationList = conversationList
    state.conversationList = JSON.parse(JSON.stringify(conversationList))

  },

  set_indexHotSearch(state, data) {
    state.indexHotSearch = {}
    for (let i = 0; i < data.length; i++) {
      data[i].type
      switch (data[i].type) {
        case 1:
          state.indexHotSearch['1'] = data[i].content
          break;
        case 2:
          state.indexHotSearch['3'] = data[i].content
          break;
        case 3:
          state.indexHotSearch['4'] = data[i].content
          break;
        case 4:
          state.indexHotSearch['0'] = data[i].content
          break;
        case 5:
          state.indexHotSearch['5'] = data[i].content
          break;
        case 6:
          state.indexHotSearch['6'] = data[i].content
          break;
        case 7:
          state.indexHotSearch['7'] = data[i].content
          break;
        case 8:
          state.indexHotSearch['2'] = data[i].content
          break;
      }

    }
  },

  set_goeasyObj(state, data) {
    state.goeasyObj = data
  },

  // 不可以看实操视频和考证题库的
  noLookShool(state, data) {
    state.menuList[6].list[1].noShow = true
    state.menuList[6].list[2].noShow = true
    // state.menuList[6].list[3].noShow = true
  },

  // 可以看实操视频和考证题库的
  yesLookShool(state, data) {
    // state.menuList[6].list[1].noShow = false
    // state.menuList[6].list[2].noShow = false
  },

  set_payVipShow(state, data) {
    if (typeof data === 'boolean') {
      state.payVipShow = data
      state.payVipIndex = 1
    } else {
      state.payVipShow = data.show
      state.payVipIndex = data.index
    }
  },

  set_payVipIndex(state, data) {
    state.payVipIndex = data
  },

  set_vipNoTimeShow(state, data) {
    state.vipNoTimeShow = data
  },
  set_signShow(state, data) {
    state.signShow = data
  },

  set_logo_color(state, data) {
    state.logo_color = data
  },
  set_nav_color(state, data) {
    state.nav_color = data
  },
  set_back_color(state, data) {
    state.back_color = data
  },

}

export const actions = {
  // 获取用户信息
  async getUserInfo(context) {
    if (localStorage.getItem('userInfo')) {
      try {
        context.commit('setuserInfo', JSON.parse(localStorage.getItem('userInfo')))
      } catch (error) {}
    }
    let token = localStorage.getItem('token')
    if (token) {
      const res = await userGetUserInfo(null)
      if (res.code == 1) {
        localStorage.setItem('userInfo', JSON.stringify(res.data))
        context.commit('setuserInfo', res.data)
      } else {
        localStorage.removeItem('userInfo')
        context.commit('setuserInfo', null)

      }
    } else {
      context.commit('setuserInfo', null)
      localStorage.removeItem('userInfo')
    }
  },
  async getUserInfo2(context) {
    return new Promise(async (resolve, reject) => {
      if (context.state.userInfo) {
        resolve(context.state.userInfo)
      } else {
        let token = localStorage.getItem('token')
        if (token) {
          const res = await userGetUserInfo(null)
          if (res.code == 1) {
            context.commit('setuserInfo', res.data)
            resolve(res.data)
          } else {
            context.commit('setuserInfo', null)
            reject(null)
          }
        } else {
          context.commit('setuserInfo', null)
          reject(null)
        }
      }

    })
  },
  // 
  createZIM(context) {
    return new Promise(async (resolve, reject) => {
      var {
        ZIM
      } = await import("zego-zim-web");
      var appID = 1472263955;
      // // 静态同步方法，创建 zim 实例，传入 AppID。
      // // create 方法仅第一次调用时会创建 ZIM 实例，后续调用会返回 null。
      ZIM.create({
        appID
      });
      // // 通过 getInstance 获取单实例，避免热更新导致 create 多次创建返回 null。
      let zim = ZIM.getInstance();
      // context.commit('set_zim', zim)
      resolve(zim)

    })
  },

  ZIMLogin(context, zim) {

    return new Promise(async (resolve, reject) => {
      let res = {
        data: {},
      };
      if (localStorage.getItem("zegoToken")) {
        res.data.token = localStorage.getItem("zegoToken");
        res.code = 1;
      } else {
        res = await getzegotoken_chat({
          user_id: context.state.userInfo.id,
        });
      }

      if (res.code == 1) {
        zim.login({
              userID: context.state.userInfo.id + "",
              userName: context.state.userInfo.nickname,
            },
            res.data.token
          )
          .then(function () {


            console.log('zim登录成功')
            context.commit('set_zimStatus', true)

            try {
              let avatar = context.state.userInfo.is_server == 1 ? context.state.userInfo.service_info.logo : context.state.userInfo.avatar
              let userName = context.state.userInfo.is_server == 1 ? context.state.userInfo.service_info.name : context.state.userInfo.nickname
              if (userName)
                zim.updateUserName(userName)
              if (avatar)
                zim.updateUserAvatarUrl(avatar).then(function ({
                  userAvatarUrl
                }) {
                  // 操作成功
                  console.log('换头像操作成功', userAvatarUrl)
                })
                .catch(function (err) {
                  // 操作失败
                  console.log('换头像操作失败')
                });
            } catch (error) {
              console.log(error)
            }

            resolve(zim)

          })
          .catch(function (err) {
            // setTimeout(() => {
            //   localStorage.removeItem("zegoToken");
            //   context.dispatch('ZIMLogin')
            // }, 100);
            // context.state.zim.logout()
          });
      }

    })

  },

  queryConversationList(context, zim) {
    return new Promise(async (resolve, reject) => {
      zim
        .queryConversationList({
          // 会话锚点，传空则代表从最新开始查询
          nextConversation: null,
          count: 20
        })
        .then(function ({
          conversationList
        }) {
          console.log('会话列表---', conversationList)
          // 查询成功，开发者需要保存和维护数组内的会话对象
          context.commit('set_conversationList', {
            conversationList: conversationList,
            zim: zim
          })

          resolve(conversationList)
        })
        .catch(function (err) {
          // 查询失败
          reject(err)
        });
    })

  },



  async getIndexRes({
    commit,
    state
  }, params) {
    const res = await getpcindex_new(params)
    if (res.code == 1) {
      commit('set_indexRes', res.data)
    }
  },

}
